$.lv = {
    videoID:"",
    init: function(){
        $(".nav-menu").on(".rvideos").live('click',function(){
            $.getJSON("/videos/getVideos",
                function(data){
                    $(".homeWrapper").empty();
                    $.each(data,function(){
                        console.log(this.video_id)
                            var video = '<a class="mainBlock videoPost" id="" href="#" ><img class="desaturate" alt="" src="'+this.thumb+'"><i></i></a>';
                            $(".homeWrapper").append(video); 
                    });
                });
        });
        $('.videoStream').find(".videoPost").live('click',function(event){
            $(this).parent().css({'z-index':'10000'});
            $(".overlay_light").show().animate({'opacity':'0.9'});
            var id = $(this).attr('id');
            var vimeo = "vimeo";
            var videoEmbed;
            if($(this).find('img').attr('src').indexOf(vimeo) != -1)
                videoEmbed =   '<iframe src="http://player.vimeo.com/video/'+id+'" width="425px" height="296px" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>';
            else
                videoEmbed = '<iframe class="youtube-player" type="text/html" width="425px" height="296px" src="http://www.youtube.com/embed/'+id+'?autoplay=1" frameborder="0" allowfullscreen ></iframe>';
            $(this).parent().empty().html(videoEmbed);
            return false;
        });
        $(".overlay_light").live('click',function(){
            $(".overlay_light").animate({'opacity':'0'}).hide();
            $(".mediaHolder").css({'z-index':'1'});
        });
        $(".moreVideoInfos").live('click',function(){
            if($(this).prev().find(".extendVideo").is(":hidden")){
                var open = $(".open");
                open.parent().prev().css({
                    "height":"0"
                });
                open.next().text("show more");
                open.removeClass("open").find(".extendVideo").slideUp();
                $(this).prev().find(".extendVideo").slideDown();
                $(this).parent().prev().css({
                    "height":"62px"
                });
                $(this).text("hide");
                $.lp.videoID = $(this).attr('id');
                $(this).prev().addClass("open");
            }else{
                $(this).prev().find(".extendVideo").slideUp();
                $(this).parent().prev().css({
                    "height":"0"
                });
                $(this).text("show more");
                $(this).prev().removeClass("open");
            }
            
            return false;
            
        });
        $(".follow").live('click',function(e){
                var this_ = $(this);
                var follower = $(this).parent(".userInfos").attr('id');
                $.post("/follow/followUser", {
                    follower:follower
                },function(data){
                    if(data){
                        this_.removeClass("follow").addClass("fl").text("Unfollow");
                    }
                });
        });
        $(".fl").live('click',function(e){
                var this_ = $(this);
                var follower = $(this).parent("").attr('id');
                $.post("/follow/unFollowUser", {
                    follower:follower
                },function(data){
                    if(data){
                        this_.removeClass("fl").addClass("follow").text("Follow");
                    }
                });
        });
        $(document).keypress(function(e) {
            if(e.which == 13) {
                if($('.videoStream').hasClass('singleVideoStream')){
                   $.lp.videoID = $('.mediaHolder').find('.videoPost').attr('id');
                   comment = $(".videoCommentBody").find('.comment').val();
                }
                else
                    var comment = $(".open").find(".videoCommentBody").find('.comment').val();
                
                
                if(comment !== ""){
                    var type = "video";
                    $.getJSON('/comment/postComment?comment='+comment+'&type='+type+'&id='+$.lp.videoID, function(data){
                        var comment = '<li>\n\
<span class="profilePicVideo" ><img src="'+data.user_profile_pic_thumb+'" width="30" height="30" /></span>\n\
                    <div class="commentInfos">\n\
                        <p class="user_name"><a href="'+data.user_name+'">'+data.user_name+'</a></p>\n\
                        <p class="added">just now</p>\n\
                    </div>\n\
                    <p class="comment_">'+data.comment+'</p>\n\
                    <div class="clearfix">\n\
                    </div>\n\
                </li>';
                        if($('.videoStream').hasClass('singleVideoStream')){
                            $(".commentstream").find("ul").prepend(comment);
                            $(".comment").val("");
                            var comments_c = parseInt($(".extendAction").find("ul").children(":first-child").text())+1;
                            $(".open").find(".extendAction").find("ul").children(":first-child").find(".commentsCount").text(comments_c +" comments");
                        }else{
                            $(".open").find(".commentstream").find("ul").prepend(comment);
                            $(".open").find(".comment").val("");
                            var comments_c = parseInt($(".open").find(".extendAction").find("ul").children(":first-child").text())+1;
                            $(".open").find(".extendAction").find("ul").children(":first-child").find(".commentsCount").text(comments_c +" comments");
                        }
                        
                    });
                }
                e.stopPropagation();
                return false;

            }
        });
        $("#likeVideo").live('click',function(){
            var this_ = $(this);
            var video_id = $(this).parents("ul").attr("id");
            if(!$(this).hasClass('likeCount_f')){
                $.post("/videos/like", {
                    video_id:video_id
                },function(){
                    this_.text(parseInt(this_.text())+1);
                    this_.attr('class','likeCount_f');
                });
            }else{
                $.post("/videos/dislike", {
                    video_id:video_id
                },function(){
                    this_.text(parseInt(this_.text())-1);
                    this_.attr('class','likeCount');
                });
            }
        });
        $("#FavVideo").live('click',function(){
            var this_ = $(this);
            var video_id = $(this).parents("ul").attr("id");
            if(!$(this).hasClass('FavCount_f')){
                
                $.post("/videos/favorite", {
                    video_id:video_id
                },function(){
                    this_.text(parseInt(this_.text())+1);
                    this_.attr('class','FavCount_f');
                });
            }
            else{
                $.post("/videos/dlFavorite", {
                    video_id:video_id
                },function(){
                    this_.text(parseInt(this_.text())-1);
                    this_.attr('class','FavCount');
                });
            }
        });
        $(".shareMedia").live('click',function(){
            $(this).next().toggle();
        });
        $("#shareVideo").find('#shareFacebook').live('click',function(){
            FB.init({appId: "264489850252668", status: true, cookie: true});
            var picture = $(this).parents('.singleVideo').find('.videoPost').find('img').attr('src');
            var link = "http://www.youtube.com/watch?v="+$(this).parents('.singleVideo').find('.videoPost').attr('id');
            var message = $(this).parents('.singleVideo').find('.description').text();
            var name = $(this).parents('.singleVideo').find('.title').find('a').text();
            postToFeed(picture,link,message,name);
        });
       
        $("#shareVideo").find('#shareTwitter').live('click',function(){
            var picture = $(this).parents('.singleVideo').find('.videoPost').find('img').attr('src');
            var link = "http://www.youtube.com/watch?v="+$(this).parents('.singleVideo').find('.videoPost').attr('id');
            var message = $(this).parents('.singleVideo').find('.description').text();
            var name = $(this).parents('.singleVideo').find('.title').find('a').text();
            
            getTinyURL(link, function(tinyurl){
                // Do something with tinyurl:
                window.open('http://twitter.com/share?url=' + tinyurl + '&text=' + name + '&via=leap', 'twitterwindow', 'height=450, width=550, top='+($(window).height()/2 - 225) +', left='+$(window).width()/2 +', toolbar=0, location=0, menubar=0, directories=0, scrollbars=0');

            });
            //We trigger a new window with the Twitter dialog, in the middle of the page
        });
    }
    
}

function ago(now,timestamp){
    
        var difference = now - timestamp;
        if(difference < 60)
            return difference+" seconds ago";
        else{
            difference = Math.round(difference / 60);
            if(difference < 60)
                return difference+" minutes ago";
            else{
                difference = Math.round(difference / 60);
                if(difference < 24)
                    return difference+" hours ago";
                else{
                    difference = Math.round(difference / 24);
                    if(difference < 7)
                        return difference+" days ago";
                    else{
                        difference = Math.round(difference / 7);
                        return difference+" weeks ago";
                    }
                }
            }
        }
    }

function postToFeed(picture,link,message,name) {

    // calling the API ...
    var obj = {
        method: 'feed',
        link: 'https://developers.facebook.com/docs/reference/dialogs/',
        picture: picture,
        name: name,
        caption: link,
        description: message
    };

    function callback(response) {
        //document.getElementById('msg').innerHTML = "Post ID: " + response['post_id'];
    }

    FB.ui(obj, callback);
}
function getTinyURL(longURL, success) {
 
    // Create unique name for callback function:
    var ud = 'json'+(Math.random()*100).toString().replace(/\./g,''),
    	// Define API URL:
        API = 'http://json-tinyurl.appspot.com/?url=';
 
    // Define a new global function:
    // (which will run the passed 'success' function:
    window[ud]= function(o){success&&success(o.tinyurl);};
 
    // Append new SCRIPT element to BODY with SRC of API:
    document.getElementsByTagName('body')[0].appendChild((function(){
 
        var s = document.createElement('script');
        s.type = 'text/javascript';
        s.src = API + encodeURIComponent(longURL) + '&callback=' + ud;
        return s;
 
    })());
 
}
 
